package http_example

import (
	"context"
	"net/http"
)

// Go1.7 引入到标准包 context

//主页
func index(w http.ResponseWriter, r *http.Request) {

	user := r.FormValue("user")
	age := r.FormValue("age")

	//给当请求附加，两个值(可用自定义路由进行上下文)
	useContext := context.WithValue(context.Background(), "user", user)
	ageContext := context.WithValue(useContext, "age", age)
	requestContext := r.WithContext(ageContext)

	//模拟将一个请求转发出去
	doHander(w, requestContext)
}

func doHander(w http.ResponseWriter, r *http.Request) {

	//我们从这个Request里取出对应的值。
	user := r.Context().Value("user").(string)
	age := r.Context().Value("age").(string)

	w.WriteHeader(http.StatusOK)
	w.Write([]byte("the user is " + user + " ,age is " + age))
}

func Run() {
	http.HandleFunc("/", index)
	http.ListenAndServe(":80", nil)
}
